using Aliphant.Mvvm.XEvent.Interface;
using Aliphant.Mvvm.XEvent.Models;
using Aliphant.Mvvm.XEvent.UI;
using GrpcClient.Managers;
using GrpcClient.UI;
using System.Collections.ObjectModel;
using System.Windows.Input;

namespace GrpcClient.ViewModels
{
    public class BrowserTabControlViewModel : BindableBase, INavigate
    {
        public BrowserTabControlViewModel()
        {
            TabManager.Instance.AddTabEvent += OnAddTab;
            TabManager.Instance.InsertTabEvent += OnInsertTab;
            TabManager.Instance.RemoveTabEvent += OnRemoveTab;
        }

        private void OnInsertTab(WebViewControl webview, int index)
        {
            TabCollection.Insert(index, webview);
            Selected = index;
        }

        private void OnAddTab(WebViewControl webview)
        {
            TabCollection.Add(webview);
            Selected = TabCollection.IndexOf(webview);
        }

        private void OnRemoveTab(WebViewControl webview)
        {
            TabCollection.Remove(webview);
            if (Selected > 1)
            {
                Selected--;
            }
        }

        private int _selected = -1;
        public int Selected { get => _selected; set => SetProperty(ref _selected, value, UpdateSelected); }

        private void UpdateSelected()
        {
            TabManager.Instance.Selected = _selected;

            if (_selected >= 0 && TabCollection.Count > _selected)
            {
                TabManager.Instance.UpdateInputUrl(TabCollection[_selected].webView.CoreWebView2?.Source ?? string.Empty);
            }
        }

        public ObservableCollection<WebViewControl> TabCollection { get; private set; } = new ObservableCollection<WebViewControl>();

        public void OnNavigateTo(NavigateParameter navigateParameter)
        {
            Init();
            Selected = TabManager.Instance.Selected;
        }

        private void Init()
        {
            TabCollection.Clear();
            var webviews = TabManager.Instance.GetAll();
            foreach (var webview in webviews)
            {
                TabCollection.Add(webview);
            }
        }

        public ICommand AddTabCommand
        {
            get => new RelayCommand<object>(obj =>
            {
                TabManager.Instance.Init();
            });
        }



    }
}
